package com.weilai.common.controller;

import com.weilai.common.model.CarouselFigure;
import com.weilai.common.service.CarouselFigureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * Created by Song on 2017/6/15.
 */
@Controller
@RequestMapping("/CarouselFigure")
public class CarouselFigureController {
    @Autowired
    CarouselFigureService carouselFigureService;

    @RequestMapping(value = "selectCarouselFigure",method = {RequestMethod.POST})
    @ResponseBody
    public List<CarouselFigure> selectCarouselFigure(){
        List<CarouselFigure> carouselFigures = carouselFigureService.selectCarouselFigure();
        return carouselFigures;
    }


    /**
     * 后台添加轮播图
     */
    @RequestMapping("addCarouselFigures")
    public Integer addCarouselFigures(@RequestParam MultipartFile file, HttpServletRequest request){
        CarouselFigure carouselFigure = new CarouselFigure();
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
//        String fileName = new Date().getTime()+".jpg";
        System.out.println(path);
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        carouselFigure.setImgurl(request.getContextPath()+"/upload/"+fileName);
        int i= carouselFigureService.addCarouselFigure(carouselFigure);
        if(i==1){
            //返回1 代表添加成功
            return 1;
        }else{
            return 0;
        }

    }

    /**
     * 查找轮播图
     */
    @RequestMapping("selectAllCarouselFigure")
    public List<CarouselFigure> selectAllCarouselFigure(){
        List<CarouselFigure> CarouselFigureList = carouselFigureService.selectAllCarouselFigure();
        return CarouselFigureList;
    }

    /**
     * 删除轮播图
     * @param carouselFigure
     */
    @RequestMapping("delCarouselFigure")
    public void delCarouselFigure(CarouselFigure carouselFigure){
        carouselFigureService.delCarouselFigure(carouselFigure);
    }

    /**
     * 修改轮播图
     * @param carouselFigure
     */
    @RequestMapping("updateCarouselFigure")
    public void updateCarouselFigure(CarouselFigure carouselFigure){
        carouselFigureService.updateCarouselFigure(carouselFigure);
    }

}
